#########################################################################################
#Promoting a Diverse Bench 
#by Jaclyn Kaslovsky, Albert Rivero, and Andrew Stone
#This file provides the code for all results in the Appendix
#########################################################################################

# Load in the necessary packages
library(xtable)
library(stargazer)
library(estimatr)
library(rms)
library(tidyverse)
library(scales)
library(dplyr)
library(ggpubr)
library(broom)
library(cowplot)
library(lubridate)
library(tictoc)
library(quanteda)
library(quanteda.textmodels)
library(lfe)
library(starpolishr)

# Set the working directory
setwd("../")
# Make a sub-folder called "Data" to load the .RData files from 
# Make a sub-folder called "Paper" to save the figures into

# Load in the senator-level, CES, and press release-level datasets
load("Data/senator_level_data.RData")
load("Data/combined_ces.RData")
load("Data/gender_press_releases.RData")
load("Data/race_press_releases.RData")
load("Data/all_press_releases.RData")

#################################
# Descriptive analyses and data #
#################################
########################################################################
# Table B.1: Numbers and rates of press releases about gender and race #
########################################################################
# About gender
table(dat_gender$nomination)
table(dat_gender$nomination, dat_gender$woman_reference_discussion)

# About race
table(dat_race$nomination, dat_race$race_reference_discussion)

###############################################################################
# Figures C.1 and C.2: Top words surrounding gender and race dictionary terms #
###############################################################################
### Figure C.1: Word stems surrounding discussion of gender ###

# Make a list of keywords to look around
keywords <- c("woman", "women", "female")

# Limit to press releases talking about gender
dat_gender_ref <- dat_gender[dat_gender$woman_reference_discussion==1,]

# Lets separate out by sentence
df_separated <- dat_gender_ref %>%
  separate_rows(sentence, sep = " \\|\\|\\| ")%>%
  filter(sentence != "")                 

# Create document corpus from statements and metadata, used to process the data
gender_corpus <- df_separated %>%
  mutate(Text = sentence, 
         Nomination = nomination,
         DocID = seq.int(nrow(df_separated))) %>%
  select(DocID, Text, senator,
         Nomination) %>% 
  corpus(text_field = "Text", 
         docid_field = "DocID")

# Find top terms
gender_dfm <- gender_corpus %>% 
  tokens(remove_punct = TRUE,
         remove_symbols = TRUE,
         remove_numbers = FALSE,
         remove_url = FALSE, 
         split_hyphens = FALSE,
         split_tags = FALSE) %>%
  tokens_select(min_nchar=2L) %>% # Remove words consisting of single character
  tokens_select(pattern = c(stopwords("en"),keywords, "ketanji", "brown", "jackson",
                            "sonia", "sotomayor", "supreme", "court", "judge", "justice",
                            "senate", "senator", "nomination", "judicial", "harriet", "miers",
                            "amy", "coney", "barrett", "elena", "kagan",
                            "confirmation", "nominee", "nominated", "serve"), 
                selection = "remove") %>% # Remove stopwords, keywords, names, generic nomination terms from the surrounding terms we're getting
  tokens_wordstem(language = quanteda_options("language_stemmer")) %>% # Get stems of words
  tokens_ngrams(n = c(1)) %>% # Return single words
  dfm() 

# Top 10 words for each nomination
top_n_terms_gender <-  topfeatures(gender_dfm, n = 10, groups = Nomination)
# Create separate data frame for each nominee based upon their top 10 words
# Barrett
barrett_gender <- data.frame(top_n_terms_gender[[1]])
barrett_gender$nominee <- "Amy Coney Barrett"
colnames(barrett_gender)[1] <- "num"
barrett_gender$top_words <- rownames(barrett_gender)
# Jackson
jackson_gender <- data.frame(top_n_terms_gender[[2]])
jackson_gender$nominee <- "Ketanji Brown Jackson"
colnames(jackson_gender)[1] <- "num"
jackson_gender$top_words <- rownames(jackson_gender)
# Kagan
kagan_gender <- data.frame(top_n_terms_gender[[3]])
kagan_gender$nominee <- "Elena Kagan"
colnames(kagan_gender)[1] <- "num"
kagan_gender$top_words <- rownames(kagan_gender)
# Miers
miers_gender <- data.frame(top_n_terms_gender[[4]])
miers_gender$nominee <- "Harriet Miers"
colnames(miers_gender)[1] <-"num"
miers_gender$top_words <- rownames(miers_gender)
# Sotomayor
sotomayor_gender <- data.frame(top_n_terms_gender[[5]])
sotomayor_gender$nominee <- "Sonia Sotomayor"
colnames(sotomayor_gender)[1] <-"num"
sotomayor_gender$top_words <- rownames(sotomayor_gender)
# Create one combined data frame
Gender_top <- bind_rows(barrett_gender, jackson_gender, kagan_gender, miers_gender, sotomayor_gender)

# Make a string of nominees
nominees <- "Harriet Miers|Sonia Sotomayor|Elena Kagan|Amy Coney Barrett|Ketanji Brown Jackson"

# Making the figure -- for each nominee, plots their top 10 words and the frequency it is used
gender_plot <- Gender_top %>%
  mutate(feature = reorder(as.factor(paste(top_words, nominee)), num)) %>%
  ggplot(aes(x = num, y = feature)) +
  geom_col(color = "black", fill ="lightgrey") +
  facet_wrap(~nominee, scales="free_y") +
  labs(x = "Number of Times Word Stem is Used", 
       y = NULL, fill = "Nominee") + 
  scale_y_discrete(labels = function(x) gsub(nominees, "", x)) +
  theme_bw() +
  theme(
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank(),
    legend.position.inside = c(0.78, 0.12),
    legend.box.background = element_rect(),
    axis.ticks.y = element_blank()
  )

# Save figure
ggsave("Paper/Figure_topwordsgender.png", width=8.5, height=6)

### Figure C.2: Word stems surrounding discussion of race ###

# Make a list of keywords to look around
keywords <- c("diverse", "diversity", "minority", "minorities", "latino", "latina", "hispanic", "racial", "race", "puerto",
              "ethnic", "black", "african")

# Limit to press releases talking about race
dat_race_ref <- dat_race[dat_race$race_reference_discussion==1,]

# Lets separate out by sentence
df_separated <- dat_race_ref %>%
  separate_rows(sentence, sep = " \\|\\|\\| ")%>%
  filter(sentence != "")                 

# Create document corpus from statements and metadata, used to process the data
race_corpus <- df_separated %>%
  mutate(Text = sentence,
         Nomination = nomination,
         DocID = seq.int(nrow(df_separated))) %>%
  select(DocID, Text, senator,
         Nomination) %>% 
  corpus(text_field = "Text", 
         docid_field = "DocID")

# Find top terms
race_dfm <- race_corpus %>% 
  tokens(remove_punct = TRUE,
         remove_symbols = TRUE,
         remove_numbers = FALSE,
         remove_url = FALSE, 
         split_hyphens = FALSE,
         split_tags = FALSE) %>%
  tokens_select(min_nchar=2L) %>% # Remove words consisting of single character
  tokens_select(pattern = c(stopwords("en"),keywords, "ketanji", "brown", "jackson",
                            "sonia", "sotomayor", "supreme", "court", "judge", "justice",
                            "senate", "senator", "nomination", "judicial", "harriet", "miers",
                            "amy", "coney", "barrett", "elena", "kagan",
                            "confirmation", "nominee", "nominated", "serve","rican"), 
                selection = "remove") %>% # Remove stopwords, keywords, names, generic nomination terms from the surrounding terms we're getting
  tokens_wordstem(language = quanteda_options("language_stemmer")) %>% # Get stems of words
  tokens_ngrams(n = c(1)) %>% # Return single words
  dfm() 

# Top 10 words for each nomination
top_n_terms_race <-  topfeatures(race_dfm, n = 10, groups = Nomination)
# Create separate data frame for each nominee based upon their top 10 words
# Jackson
jackson_race <- data.frame(top_n_terms_race[[1]])
jackson_race$nominee <- "Ketanji Brown Jackson"
colnames(jackson_race)[1] <- "num"
jackson_race$top_words <- rownames(jackson_race)
# Sotomayor
sotomayor_race <- data.frame(top_n_terms_race[[2]])
sotomayor_race$nominee <- "Sonia Sotomayor"
colnames(sotomayor_race)[1] <-"num"
sotomayor_race$top_words <- rownames(sotomayor_race)
# Create one combined data frame
Race_top <- bind_rows(jackson_race,sotomayor_race)

# Making the figure -- for each nominee, plots their top 10 words and the frequency it is used
race_plot <- Race_top %>%
  mutate(feature = reorder(as.factor(paste(top_words, nominee)), num)) %>%
  ggplot(aes(x = num, y = feature)) +
  geom_col(color = "black", fill ="lightgrey") +
  facet_wrap(~nominee, scales="free_y") +
  labs(x = "Number of Times Word Stem is Used", 
       y = NULL, fill = "Nominee") + 
  scale_y_discrete(labels = function(x) gsub(nominees, "", x)) +
  theme_bw() +
  scale_x_continuous(limits=c(0,150)) +
  theme(
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank(),
    legend.position.inside = c(0.78, 0.12),
    legend.box.background = element_rect(),
    axis.ticks.y = element_blank()
  )
# Save figure
ggsave("Paper/Figure_topwordsrace.png", width=6, height=3.75)

###################################################################################################
# Figures D.1 and D.2: Appendix figures of sentiment of use of race/gender language by nomination #
###################################################################################################
# Gender
# Limit to press releases talking about gender
dat_gender_ref <- dat_gender[dat_gender$woman_reference_discussion==1,]
# For each nomination, determine number of positive messages about gender and number of total messages about gender
gender_sentiment <- data.frame(cbind(table(dat_gender_ref$nomination, dat_gender_ref$woman_positive_sentiment)[,2],table(dat_gender_ref$nomination, dat_gender_ref$woman_reference_discussion)[,1]))
# Column names
colnames(gender_sentiment) <- c("positive","total")
# Ratio of positive gender messages to total gender messages
gender_sentiment$ratio_positive <- gender_sentiment$positive/(gender_sentiment$total)
# Nomination names
gender_sentiment$nominee <- c("Barrett","Jackson","Kagan","Miers","Sotomayor")

pdf("Paper/gender-sentiment.pdf", width=8.5, height=5)
gender_sentiment %>%
  ggplot(aes(x=nominee, y=ratio_positive)) + 
  geom_bar(stat="identity", position=position_dodge(), alpha=0.7) +
  scale_fill_grey() +
  scale_y_continuous(labels = percent) +
  theme_bw()  + theme(legend.title=element_blank()) +
  ylab("% of Releases Discussing Gender That Are Positive in Sentiment") + xlab("Nomination") + theme(legend.position = "bottom") +
  coord_flip()
dev.off()

# Race
# Limit to press releases talking about race
dat_race_ref <- dat_race[dat_race$race_reference_discussion==1,]
# For each nomination, determine number of positive messages about race and number of total messages about race
race_sentiment <- data.frame(cbind(table(dat_race_ref$nomination, dat_race_ref$race_positive_sentiment)[,2],table(dat_race_ref$nomination, dat_race_ref$race_reference_discussion)[,1]))
# Column names
colnames(race_sentiment) <- c("positive","total")
# Ratio of positive gender messages to total race messages
race_sentiment$ratio_positive <- race_sentiment$positive/(race_sentiment$total)
# Nomination names
race_sentiment$nominee <- c("Jackson","Sotomayor")

pdf("Paper/race-sentiment.pdf", width=8.5, height=5)
race_sentiment %>%
  ggplot(aes(x=nominee, y=ratio_positive)) +
  geom_bar(stat="identity", position=position_dodge(), alpha=0.7) +
  scale_fill_grey() +
  scale_y_continuous(labels = percent, limits=c(0,1)) +
  theme_bw()  + theme(legend.title=element_blank()) +
  ylab("% of Releases Discussing Race That Are Positive in Sentiment") + xlab("Nomination") + theme(legend.position = "bottom") +
  coord_flip()
dev.off()

#####################################################################
# Figure E.1: Mentions of qualifications by nominee race and gender #
#####################################################################
# Let's separate out by sentence
df_separated <- dat_total %>%
  separate_rows(sentence, sep = " \\|\\|\\| ")%>%
  filter(sentence != "")    

# Let's separate out by keyword phrase
df_separated_2 <- dat_total %>%
  separate_rows(phrase, sep = " \\|\\|\\| ")%>%
  filter(phrase != "")    

# Combine the two
df_separated$phrase <- df_separated_2$phrase

# Make a variable that equals one so we can collapse our data back to the press release level (to avoid counting the same press release twice for the same keyword type as this analysis is at the press release level)
df_separated$mentions <- 1
# If keyword was qualified or qualifications, call it the same "qualifications or qualified"
df_separated$phrase[df_separated$phrase=="qualified"|df_separated$phrase=="qualifications"] <- "qualifications or qualified"
# Collapsing down to press release level
dat_collapse <- df_separated %>% group_by(docname,phrase,senator,positive,nomination) %>% summarize(mentions=sum(mentions))

# Now collapse to the nomination level for each kind of reference ("qualifications or qualified" or "record"), positive or non-positive mentions
dat_collapse$mentions <- 1
dat_collapse <- df_separated %>% group_by(phrase,nomination,positive) %>% summarize(mentions=sum(mentions))

# Coding which nominees are women
dat_collapse$woman <- 0 
dat_collapse$woman[dat_collapse$nomination=="miers"|dat_collapse$nomination=="sotomayor"|
                     dat_collapse$nomination=="kagan"|dat_collapse$nomination=="barrett"|
                     dat_collapse$nomination=="jackson"] <- 1
dat_collapse$woman <- as.factor(dat_collapse$woman)

# Type of reference, will be used when plotting
features <- dat_collapse$phrase %>% unique() %>% paste(collapse = "|")

# Removing NA codings
dat_collapse <- dat_collapse[!is.na(dat_collapse$positive),]
# Upper case
dat_collapse$nomination <- str_to_title(dat_collapse$nomination)
# Coding race/gender identity of nominees
dat_collapse$identity <- "White Man"
dat_collapse$identity[dat_collapse$nomination=="Miers"|dat_collapse$nomination=="Kagan"|
                        dat_collapse$nomination=="Barrett"] <- "White Woman"
dat_collapse$identity[dat_collapse$nomination=="Jackson"|dat_collapse$nomination=="Sotomayor"] <- "Non-White Woman"

# Just non-positive data
dat_non_pos <- dat_collapse[dat_collapse$positive==0,]
# Just positive data
dat_pos <- dat_collapse[dat_collapse$positive==1,]

# Graph of non-positive mentions (these are negative or neutral)
nonpos <- dat_non_pos %>%
  group_by(phrase) %>%
  mutate(
    feature = reorder(as.factor(paste(phrase, str_to_title(nomination))), -mentions)  # Order by mentions for each keyword
  ) %>%
  ungroup() %>%
  ggplot(aes(x = feature, y = mentions, fill = identity)) +
  facet_wrap(~phrase, scales = "free_y") +  # Free y-axis scaling for each facet
  scale_x_discrete(labels = function(x) gsub(features, "", x)) +
  ylim(0,600) + 
  geom_col() +
  labs(y = "Number of Non-Positive Press Releases Mentioning Word", 
       x = NULL, fill = "identity") +
  theme_bw() +
  coord_flip()+
  theme(legend.title=element_blank())

positive <- dat_pos %>%
  group_by(phrase) %>%
  mutate(
    feature = reorder(as.factor(paste(phrase, str_to_title(nomination))), -mentions)  # Order by mentions for each keyword
  ) %>%
  ungroup() %>%
  ggplot(aes(x = feature, y = mentions, fill = identity)) +
  facet_wrap(~phrase, scales = "free_y") +  # Free y-axis scaling for each facet
  scale_x_discrete(labels = function(x) gsub(features, "", x)) +
  ylim(0,600) + 
  geom_col() +
  labs(y = "Number of Positive Press Releases Mentioning Word", 
       x = NULL, fill = "identity") +
  theme_bw() +
  coord_flip()+
  theme(legend.title=element_blank())

# Save figure
total <- ggarrange(positive,nonpos,ncol=1)
ggsave("Paper/qualifications.png", width=7, height=5)

rm(list=setdiff(ls(), c("dat_gender", "dat_race","senator_level_data")))

####################################
# Senator-level messaging analyses #
####################################
#############################################################################
# Figure F.1: Senator discussion of nominee gender and race (combined plot) #
#############################################################################
# Make descriptive plots by Democratic and Republican nominees
addline_format <- function(x,...){
  y <- gsub('\\s', '\n', x)
  gsub('of\nColor', 'of Color', y)
}

### Gender ###
# Using press release level data, create descriptive groups by senator gender and partisanship; determine mean and SD of that group's discussion of gender, plot it
gender <- dat_gender %>%
  mutate(senator_descriptive = case_when(female == 1 & democrat == 1 ~ "Democratic\nWoman",
                                         female == 1 & democrat == 0 ~ "Republican\nWoman",
                                         female == 0 & democrat == 1 ~ "Democratic\nMan",
                                         female == 0 & democrat == 0 ~ "Republican\nMan"),
         senator_descriptive = factor(senator_descriptive, levels = c("Republican\nMan",
                                                                      "Republican\nWoman",
                                                                      "Democratic\nMan",
                                                                      "Democratic\nWoman"))) %>%
  group_by(senator_descriptive) %>%
  dplyr::summarize(mean_dv = mean(woman_reference_discussion, na.rm = T),
                   se_dv = sqrt(var(woman_reference_discussion, na.rm = T)/n()),
                   lb = mean_dv - 1.96*se_dv,
                   ub = mean_dv + 1.96*se_dv,
                   n = n(),
                   mean_dv = mean_dv * 100,
                   lb = lb * 100,
                   ub = ub * 100) %>%
  mutate(senator_descriptive = paste0(senator_descriptive, " (n=", n, ")")) %>%
  ggplot(aes(x=senator_descriptive, y=mean_dv, color=senator_descriptive)) + 
  geom_point(stat="identity", alpha=0.7, size=2.5, shape=c(16,16,17,17)) +
  geom_linerange(aes(ymin=lb, ymax=ub), linewidth=1)+
  scale_fill_grey() +
  scale_color_manual(values = c("Blue", "Blue", "Red", "Red")) +
  scale_y_continuous(limits = c(-5, 100)) +
  theme_classic()  + theme(legend.title=element_blank()) +
  ylab("Descriptive Messaging Percentage (Gender)") + 
  xlab("Senator Characteristics") + 
  theme(legend.position = "none") +
  coord_flip()

# Looking at the sentiment of messages

dat_gender %>% filter(woman_reference_discussion == 1) %>% pull(woman_positive_sentiment) %>% mean(na.rm=T)
dat_race %>% filter(race_reference_discussion == 1) %>% pull(race_positive_sentiment) %>% mean(na.rm=T)

### Race ###
# Using press release level data, create descriptive groups by senator race and partisanship; determine mean and SD of that group's discussion of race, plot it
race <- dat_race %>%
  mutate(senator_descriptive = case_when(minority == 1 & democrat == 1 ~ "Democrat\nof Color",
                                         minority == 1 & democrat == 0 ~ "Republican\nof Color",
                                         minority == 0 & democrat == 1 ~ "White\nDemocrat",
                                         minority == 0 & democrat == 0 ~ "White\nRepublican"),
         senator_descriptive = factor(senator_descriptive, levels = c("White\nRepublican",
                                                                      "Republican\nof Color",
                                                                      "White\nDemocrat",
                                                                      "Democrat\nof Color"))) %>%
  group_by(senator_descriptive) %>%
  dplyr::summarize(mean_dv = mean(race_reference_discussion, na.rm = T),
                   se_dv = sqrt(var(race_reference_discussion, na.rm = T)/n()),
                   lb = mean_dv - 1.96*se_dv,
                   ub = mean_dv + 1.96*se_dv,
                   n = n(),
                   mean_dv = mean_dv * 100,
                   lb = lb * 100,
                   ub = ub * 100) %>%
  mutate(senator_descriptive = paste0(senator_descriptive, " (n=", n, ")")) %>%
  ggplot(aes(x=senator_descriptive, y=mean_dv, color=senator_descriptive)) + 
  geom_point(stat="identity", alpha=0.7, size=2.5, shape=c(16,16,17,17)) +
  geom_linerange(aes(ymin=lb, ymax=ub), linewidth=1)+
  scale_fill_grey() +
  scale_color_manual(values = c("Blue", "Red", "Blue", "Red")) +
  scale_y_continuous(limits = c(-5, 100)) +
  theme_classic()  + theme(legend.title=element_blank()) +
  ylab("Descriptive Messaging Percentage (Race/Ethnicity)") +
  xlab("") + 
  theme(legend.position = "none") +
  coord_flip()

# Combine the graphs
combined <- ggarrange(gender, race)

# Save
ggsave("Paper/Figure_discussion.png",combined, width=10, height=3.5)

# All Democrats vs. Republicans for race (discussed in main text)
race2 <- dat_race %>%
  mutate(senator_descriptive = case_when(democrat == 1 ~ "Democrat",
                                         democrat == 0 ~ "Republican")) %>%
  group_by(senator_descriptive) %>%
  dplyr::summarize(mean_dv = mean(race_reference_discussion, na.rm = T),
                   se_dv = sqrt(var(race_reference_discussion, na.rm = T)/n()),
                   lb = mean_dv - 1.96*se_dv,
                   ub = mean_dv + 1.96*se_dv,
                   n = n(),
                   mean_dv = mean_dv * 100,
                   lb = lb * 100,
                   ub = ub * 100)

#####################################################
# Table F.1: Replacing Democrat with NOMINATE score #
#####################################################
# Binary measure
either_anydw <- lm(any_positive_either ~ dwnom1 + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                     + state + nomination, data=senator_level_data)
# Same model, but with robust SEs clustered by state
either_any_robustdw <- lm_robust(any_positive_either ~ dwnom1 + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                   + state + nomination, data=senator_level_data, clusters = state)

# Count measure
either_countdw <- lm(number_positive_either ~ dwnom1 + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                       + state + nomination, data=senator_level_data)
# Same model, but with robust SEs clustered by state
either_count_robustdw <- lm_robust(number_positive_either ~ dwnom1 + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                     + state + nomination, data=senator_level_data, clusters=state)

# Regressions into a latex table
main.reg.latexdw <- stargazer(either_anydw,either_countdw,
                              model.numbers=FALSE,
                              digits=2, dep.var.labels=c("Any Discussion","Count of Discussion"),
                              covariate.labels=c("First Dim. DW-NOMINATE","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                              star.cutoffs=c(0.10,0.05),
                              no.space=T,
                              notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of a Senator’s messaging about a nominee’s descriptive traits as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                              omit = c("state[A-Z][A-Z]","nomination*"),
                              omit.stat = c("adj.rsq","f"),
                              title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics, Replacing Democrat with DW-NOMINATE",
                              label = "ols-senator-messaging-about-both-dw",
                              notes.append = FALSE,notes.label = "",
                              add.lines=list(c("State Fixed Effects","\\cmark","\\cmark"),
                                             c("Nomination Fixed Effects","\\cmark","\\cmark")),
                              font.size = "small",
                              se = starprep(either_any_robustdw,either_count_robustdw),
                              p = starprep(either_any_robustdw,either_count_robustdw, stat = "p.value"),
                              table.placement = "H")
# Outputting
cat(main.reg.latexdw, sep = '\n', file = "Paper/Table2_dw.tex")

############################################################################
# Table F.2: Subsetting by Southern states (members of former Confederacy) #
############################################################################
# List of southern states
southern_states <- c("AL", "AR", "FL", "GA", "LA", "MS", "NC", "SC", "TN", "TX", "VA")

# Subset the dataset for Southern states
data_south <- subset(senator_level_data, state %in% southern_states)

# Subset the dataset for non-Southern states
data_non_south <- subset(senator_level_data, !(state %in% southern_states))

# Binary measure, South
any_south <- lm(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                  + state + nomination, data=data_south)

any_robust_south <- lm_robust(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                + state + nomination, data=data_south, clusters = state)
# Count measure, South
count_south <- lm(number_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                    + state + nomination, data=data_south)

count_robust_south <- lm_robust(number_positive_either ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                  + state + nomination, data=data_south, clusters=state)

# Binary measure, non-South
any_non_south <- lm(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                      + state + nomination, data=data_non_south)

any_robust_non_south <- lm_robust(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                    + state + nomination, data=data_non_south, clusters = state)
# Count measure, non-South
count_non_south <- lm(number_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                        + state + nomination, data=data_non_south)

count_robust_non_south <- lm_robust(number_positive_either ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election +
                                      + state + nomination, data=data_non_south, clusters=state)

# Regressions into a latex table
south.reg.latex <- stargazer(any_south,count_south,any_non_south,count_non_south,
                            column.separate = c(2,2),column.sep.width = ".5pt",
                            column.labels = c("Southern States","Non-Southern States"), model.numbers=FALSE,
                            digits=2, dep.var.labels=c("Any Discussion","Count of Discussion","Any Discussion","Count of Discussion"),
                            covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                            star.cutoffs=c(0.10,0.05),
                            no.space=T,
                            notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of a Senator’s messaging about a nominee’s descriptive traits as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                            omit = c("state[A-Z][A-Z]","nomination*"),
                            omit.stat = c("adj.rsq","f"),
                            title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics Subset by Membership in the Former Confederacy",
                            label = "ols-south",
                            notes.append = FALSE,notes.label = "",
                            add.lines=list(c("State Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark"),
                                           c("Nomination Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark")),
                            font.size = "small",
                            se = starprep(any_robust_south,count_robust_south,any_robust_non_south,count_robust_non_south),
                            p = starprep(any_robust_south,count_robust_south,any_robust_non_south,count_robust_non_south, stat = "p.value"),
                            table.placement = "H")
# Outputting
cat(south.reg.latex, sep = '\n', file = "Paper/Table2_South.tex")

###################################
# Table F.3: Logistic regressions #
###################################
# Binary measure
any_logit <- lrm(any_positive_either ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                 + state + nomination, data=senator_level_data, x=T, y=T)
any_logit_robust <- robcov(any_logit, cluster=senator_level_data$state)

# Regression into a latex table
reg.logit <- stargazer(any_logit_robust,
                          digits=2, dep.var.labels=c("Any Discussion"),
                          covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                          star.cutoffs=c(0.10,0.05),
                          no.space=T,
                          notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from logistic regression of a Senator's messaging about a nominee's gender and race 
                              as a function of the Senator's characteristics. Robust standard errors 
                                              clustered at the state level are 
                                              denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}",
                          omit.stat = c("adj.rsq","f"), 
                          omit = c("state=","nomination*"),
                          title = "Senator Messaging about Nominee Descriptive Characteristics: Logistic Regression",
                          label = "logit-senator-messaging",
                          notes.append = FALSE,notes.label = "",
                          add.lines=list(c("State Dummy Variables","\\cmark"),
                                         c("Nomination Dummy Variables","\\cmark")),
                          font.size = "small",
                          table.placement = "H")
# Outputting
cat(reg.logit, sep = '\n', file = "Paper/gender_race_logit.tex")

#################################################
# Table F.4: Logged continuous outcome variable #
#################################################
# Creating logged number of mentions outcome
senator_level_data$log_number_discussion_either_mention <- log(senator_level_data$number_positive_either + 0.01)

# Count measure, logged
count_log <- lm(log_number_discussion_either_mention ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                + state + nomination, data=senator_level_data)
summary(count_log)

count_log_robust <- lm_robust(log_number_discussion_either_mention ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                              + state + nomination, data=senator_level_data, clusters=state)
summary(count_log_robust)

# Regression into a latex table
reg.logged.latex <- stargazer(count_log,model.numbers=FALSE,
                              digits=2, dep.var.labels=c("Logged Count of Trait Discussion"),
                              covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                              star.cutoffs=c(0.10,0.05),
                              no.space=T,
                              notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regression of a Senator’s messaging about a nominee’s descriptive traits as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                              omit = c("state[A-Z][A-Z]","nomination*"),
                              omit.stat = c("adj.rsq","f"),
                              title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics: Logged Continuous DV",
                              label = "ols-senator-messaging-about-both-logged-dv",
                              notes.append = FALSE,notes.label = "",
                              add.lines=list(c("State Fixed Effects","\\cmark"),
                                             c("Nomination Fixed Effects","\\cmark")),
                              font.size = "small",
                              se = starprep(count_log_robust),
                              p = starprep(count_log_robust, stat = "p.value"),
                              table.placement = "H")
# Outputting
cat(reg.logged.latex, sep = '\n', file = "Paper/senator_level_regression_logged_dv.tex")

####################################################
# Table F.5: Separated by gender or race messaging #
####################################################
# Binary measure, gender
gender_any <- lm(any_positive_gender ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                 + state + nomination, data=senator_level_data)
summary(gender_any)

gender_any_robust <- lm_robust(any_positive_gender ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election 
                               + state + nomination, data=senator_level_data, clusters=state)
summary(gender_any_robust)

# Count measure, gender
gender_count <- lm(number_positive_gender ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                   + state + nomination, data=senator_level_data)
summary(gender_count)

gender_count_robust <- lm_robust(number_positive_gender ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election
                                 + state + nomination, data=senator_level_data, clusters=state)
summary(gender_count_robust)

# Binary measure, race
race_any <- lm(any_positive_race ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
               + state + nomination, data=senator_level_data)
summary(race_any)

race_any_robust <- lm_robust(any_positive_race ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                             + state + nomination, data=senator_level_data, clusters=state)
summary(race_any_robust)

# Count measure, race
race_count <- lm(number_positive_race ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                 + state + nomination, data=senator_level_data)
summary(race_count)

race_count_robust <- lm_robust(number_positive_race ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                               + state + nomination, data=senator_level_data, clusters=state)
summary(race_count_robust)

# Regressions into a latex table
sep.reg.latex <- stargazer(gender_any,gender_count,race_any,race_count,
                           column.labels = c("Gender", "Race/Ethnicity"), model.numbers=FALSE,
                           column.separate = c(2,2),
                           digits=2, dep.var.labels=c("Any Discussion","Count of Discussion","Any Discussion","Count of Discussion"),
                           covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                           star.cutoffs=c(0.10,0.05),
                           no.space=T,
                           notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of a Senator’s messaging about a nominee’s gender (columns 1 and 2) 
                              and race (columns 3 and 4) as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                           omit = c("state[A-Z][A-Z]","nomination*"),
                           omit.stat = c("adj.rsq","f"),
                           title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics Separated by Trait",
                           label = "ols-senator-messaging-about-sep",
                           notes.append = FALSE,notes.label = "",
                           add.lines=list(c("State Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark"),
                                          c("Nomination Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark")),
                           font.size = "footnotesize",
                           se = starprep(gender_any_robust,gender_count_robust,race_any_robust,race_count_robust),
                           p = starprep(gender_any_robust,gender_count_robust,race_any_robust,race_count_robust, stat = "p.value"),
                           table.placement = "H")
# Outputting
cat(sep.reg.latex, sep = '\n', file = "Paper/Table2_sep.tex")

######################################
# Table F.6: Intersectional Analysis #
######################################
# Binary measure, gender and race
race_gender_any <- lm(any_race_gender_positive ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                      + state + nomination, data=senator_level_data)
summary(race_gender_any)

race_gender_any_robust <- lm_robust(any_race_gender_positive ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                                    + state + nomination, data=senator_level_data, clusters=state)
summary(race_gender_any_robust)

# Count measure, gender and race
race_gender_count <- lm(number_race_gender_positive ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                        + state + nomination, data=senator_level_data)
summary(race_gender_count)

race_gender_count_robust <- lm_robust(number_race_gender_positive ~ democrat + party_leader + on_sjc +  freshman + female + same_race + marginal_party_didnt_win*up_for_election
                                      + state + nomination, data=senator_level_data, clusters=state)
summary(race_gender_count_robust)

# Regressions into a latex table
both.reg.latex <- stargazer(race_gender_any,race_gender_count,
                            digits=2, dep.var.labels=c("Any Discussion","Count of Discussion"),
                            covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Electorally Marginal", "Up for Election","Electorally Marginal x Up for Election"),
                            star.cutoffs=c(0.10,0.05),
                            no.space=T,
                            notes="\\parbox[t]{0.8\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of a Senator’s messaging about a nominee's race and gender as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. Data are subset to the Sotomayor and Jackson nominations. Outcome variables capture messaging that discusses both a nominee's race and gender. $^{**}p<0.05$; $^*p<0.1$.}", 
                            omit = c("state[A-Z][A-Z]","nomination*"),
                            omit.stat = c("adj.rsq","f"),
                            title = "Determinants of Senator Messaging about Nominee Race and Gender (Intersectionality)",
                            label = "racegender",
                            notes.append = FALSE,notes.label = "",
                            add.lines=list(c("State Fixed Effects","\\cmark","\\cmark"),
                                           c("Nomination Fixed Effects","\\cmark","\\cmark")),
                            font.size = "small",
                            se = starprep(race_gender_any_robust, race_gender_count_robust),
                            p = starprep(race_gender_any_robust, race_gender_count_robust, stat = "p.value"),
                            table.placement = "H")
# Outputting
cat(both.reg.latex, sep = '\n', file = "Paper/gender_race_senator_level_regression_revised.tex")

#############################################################
# Table F.7: Interaction with copartisanship with president #
#############################################################
# Binary measure
any_copartisan_interacted <- lm(any_positive_either ~ democrat + party_leader*copartisan_president + on_sjc*copartisan_president + freshman*copartisan_president + 
                                  female*copartisan_president + same_race*copartisan_president + marginal_party_didnt_win*up_for_election*copartisan_president + state + nomination, data=senator_level_data)

any_robust_copartisan_interacted <- lm_robust(any_positive_either ~ democrat + party_leader*copartisan_president + on_sjc*copartisan_president + freshman*copartisan_president + 
                                                female*copartisan_president + same_race*copartisan_president + marginal_party_didnt_win*up_for_election*copartisan_president + state + nomination, 
                                              data=senator_level_data, clusters = state)

# Count measure
count_copartisan_interacted <- lm(number_positive_either ~ democrat + party_leader*copartisan_president + on_sjc*copartisan_president + freshman*copartisan_president + 
                                  female*copartisan_president + same_race*copartisan_president + marginal_party_didnt_win*up_for_election*copartisan_president + state + nomination, data=senator_level_data)

count_robust_copartisan_interacted <- lm_robust(number_positive_either ~ democrat + party_leader*copartisan_president + on_sjc*copartisan_president + freshman*copartisan_president + 
                                                  female*copartisan_president + same_race*copartisan_president + marginal_party_didnt_win*up_for_election*copartisan_president + state + nomination, 
                                                data=senator_level_data, clusters=state)

# Regressions into a latex table
copartisan.outpartisan.reg.latex.interacted <- stargazer(any_copartisan_interacted,count_copartisan_interacted,
                                              digits=2, dep.var.labels=c("Any Discussion","Count of Discussion"),
                                              covariate.labels=c("Democrat","Party Leader","Copartisan of President","On Judiciary Committee","Freshman","Woman","Same Race","Electorally Marginal", "Up for Election",
                                                                 "Party Leader x Copartisan","On SJC x Copartisan","Freshman x Copartisan","Woman x Copartisan","Same Race x Copartisan",
                                                                 "Electorally Marginal x Up for Election","Electorally Marginal x Copartisan","Up for Election x Copartisan","Electorally Marginal x Up for Election x Copartisan"),
                                              star.cutoffs=c(0.10,0.05),
                                              no.space=T,
                                              notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of a Senator’s messaging about a nominee’s descriptive traits as a function of the Senator's characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                                              omit = c("state[A-Z][A-Z]","nomination*"),
                                              omit.stat = c("adj.rsq","f"),
                                              title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics: Interactions with Copartisanship",
                                              label = "ols-copartisan-outpartisan",
                                              notes.append = FALSE,notes.label = "",
                                              add.lines=list(c("State Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark"),
                                                             c("Nomination Fixed Effects","\\cmark","\\cmark","\\cmark","\\cmark")),
                                              font.size = "footnotesize",
                                              se = starprep(any_robust_copartisan_interacted,count_robust_copartisan_interacted),
                                              p = starprep(any_robust_copartisan_interacted,count_robust_copartisan_interacted, stat = "p.value"),
                                              table.placement = "H")
# Outputting
cat(copartisan.outpartisan.reg.latex.interacted, sep = '\n', file = "Paper/Table2_Copartisan_Outpartisan_Interacted.tex")

#######################################################
# Table F.8: Accounting for first day position taking #
#######################################################
# Binary model
either_any_first_day <- lm(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election + positive_position_day_one +
                   + state + nomination, data=senator_level_data)
summary(either_any_first_day)

either_any_robust_first_day <- lm_robust(any_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election + positive_position_day_one +
                                 + state + nomination, data=senator_level_data, clusters = state)
summary(either_any_robust_first_day)

# Count model
either_count_first_day <- lm(number_positive_either ~ democrat + party_leader + on_sjc + freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election + positive_position_day_one +
                     + state + nomination, data=senator_level_data)
summary(either_count_first_day)

either_count_robust_first_day <- lm_robust(number_positive_either ~ democrat + party_leader + on_sjc +  freshman + female + same_race + copartisan_president + marginal_party_didnt_win*up_for_election + positive_position_day_one +
                                   + state + nomination, data=senator_level_data, clusters=state)
summary(either_count_robust_first_day)

# Regressions into a latex table
main.reg.latex <- stargazer(either_any_first_day,either_count_first_day,
                            model.numbers=FALSE,
                            #column.separate = c(2,2),
                            digits=2, dep.var.labels=c("Any Discussion","Count of Discussion"),
                            covariate.labels=c("Democrat","Party Leader","On Judiciary Committee","Freshman","Woman","Same Race","Copartisan of President","Electorally Marginal", "Up for Election","Positive Position Day One","Electorally Marginal x Up for Election"),
                            star.cutoffs=c(0.10,0.05),
                            no.space=T,
                            notes="\\parbox[t]{\\textwidth}{\\footnotesize \\textit{Note}: The table shows the results from OLS regressions of senator messaging about a nominee’s descriptive traits as a function of senator characteristics. 
          Robust standard errors clustered at the state level are denoted in parentheses. $^{**}p<0.05$; $^*p<0.1$.}", 
                            omit = c("state[A-Z][A-Z]","nomination*"),
                            omit.stat = c("adj.rsq","f"),
                            title = "Determinants of Senator Messaging about Nominee Descriptive Characteristics: First Day Position Taking",
                            label = "ols-first-day",
                            notes.append = FALSE,notes.label = "",
                            add.lines=list(c("State Fixed Effects","\\cmark","\\cmark"),
                                           c("Nomination Fixed Effects","\\cmark","\\cmark")),
                            font.size = "small",
                            se = starprep(either_any_robust_first_day,either_count_robust_first_day),
                            p = starprep(either_any_robust_first_day,either_count_robust_first_day, stat = "p.value"),
                            table.placement = "H")
# Outputting
cat(main.reg.latex, sep = '\n', file = "Paper/Table2_First_Day.tex")

rm(list = ls())

#############################
# Respondent-level analyses #
#############################
# Load the data
load("Data/combined_ces.RData")

# Going to run all of the regressions first, output individual tables, then combine into one figure
# Regression formula that we will use to run the models, 4pt approval outcome, respondent-level fixed effects, no instrumenting, clustered SEs by respondent
std_formula <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                         I(log(total_nominee_messages + 0.01)) +
                         extremity + seniority + I(seniority^2) + majority +
                         female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
# Version without afam
std_formula_alt <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                         I(log(total_nominee_messages + 0.01)) +
                         extremity + seniority + I(seniority^2) + majority +
                         female + latino + votepct + chair | respondentid | 0 | respondentid)

############################################################
# Table G.1: Full gender analysis results, all respondents #
############################################################
# Pooled model (all nominations), gender messaging
Pooled.g <- felm(std_formula, data=ces_total)
# Sotomayor model
Sotomayor.g <- felm(std_formula_alt, data=ces_total %>% filter(nomination == "sotomayor"))
# Kagan model
Kagan.g <- felm(std_formula_alt, data=ces_total %>% filter(nomination == "kagan"))
# Barrett model
Barrett.g <- felm(std_formula, data=ces_total %>% filter(nomination == "barrett"))
# Jackson model
Jackson.g <- felm(std_formula, data=ces_total %>% filter(nomination == "jackson"))

# Putting results in stargazer table
total_full <- stargazer(Pooled.g,Sotomayor.g,Kagan.g,Barrett.g,Jackson.g,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                        covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare", "Committee Chair", "Any Positive Gender Message x Copartisan"),
                        notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabgender",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Gender, Copartisanship, and Senator Approval")
# Outputting
cat(total_full, sep = '\n', file = "Paper/Table_full_gender.tex")

# Removing unnecessary objects
rm(Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

############################################################
# Table G.2: Full gender analysis results, men respondents #
############################################################
# Subset to non-women
man.respondents <- ces_total[which(ces_total$woman == 0),]

# Running all of the models, same formula (model) as for all respondents above but on the men respondents only
Pooled.g <- felm(std_formula, man.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, man.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, man.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Putting results in stargazer table
total_men <- stargazer(Pooled.g,Sotomayor.g, Kagan.g, Barrett.g, Jackson.g,
                       add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                       notes.append = FALSE, notes.label = "",
                       report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                       omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                       dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                       model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                       covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare", "Committee Chair", "Any Positive Gender Message x Copartisan"),
                       notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                       label="tabmen",
                       digits=2,
                       digits.extra = 0,column.sep.width = "-8pt",
                       title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Men")
# Outputting
cat(total_men, sep = '\n', file = "Paper/Table_men_gender.tex")

rm(Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

##############################################################
# Table G.3: Full gender analysis results, women respondents #
##############################################################
# Subset to women
woman.respondents <- ces_total[which(ces_total$woman == 1),]

# Running all of the models, same formula (model) as for all respondents above but on the women respondents only
Pooled.g <- felm(std_formula, woman.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, woman.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, woman.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Putting results in stargazer table
total_women <- stargazer(Pooled.g,Sotomayor.g, Kagan.g, Barrett.g, Jackson.g,
                         add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                         notes.append = FALSE, notes.label = "",
                         report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                         omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                         dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                         model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                         covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare", "Committee Chair", "Any Positive Gender Message x Copartisan"),
                         notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                         label="tabwomen",
                         digits=2,
                         digits.extra = 0,column.sep.width = "-8pt",
                         title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Women")

cat(total_women, sep = '\n', file = "Paper/Table_women_gender.tex")

rm(Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

##########################################################
# Table G.4: Full race analysis results, all respondents #
##########################################################
# Regression formula, respondent-level fixed effects, no instrumenting, clustered SEs by respondent
formula_race <- formula(senator_approval2 ~ binary_positive_race*match_senator_party_leaners +
                          I(log(total_nominee_messages + 0.01)) +
                          extremity + seniority + I(seniority^2) + majority +
                          female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
# Without afam
formula_race_alt <- formula(senator_approval2 ~ binary_positive_race*match_senator_party_leaners +
                          I(log(total_nominee_messages + 0.01)) +
                          extremity + seniority + I(seniority^2) + majority +
                          female + latino + votepct + chair | respondentid | 0 | respondentid)

# Pooled model (all nominations), race messaging
Pooled.r <- felm(formula_race, data=ces_total)
summary(Pooled.r)

# Sotomayor model
Sotomayor.r <- felm(formula_race_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

# Jackson model
Jackson.r <- felm(formula_race, data=ces_total %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Putting results in stargazer table
total_race <- stargazer(Pooled.r, Sotomayor.r, Jackson.r,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                        covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Race Message x Copartisan"),
                        notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabrace",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Race, Copartisanship, and Senator Approval")
# Outputting
cat(total_race, sep = '\n', file = "Paper/Table_full_race.tex")

rm(Pooled.r, Sotomayor.r, Jackson.r)

#####################################################################
# Table G.5: Full race analysis results, different race respondents #
#####################################################################
# Subsetting to same race respondents (Hispanic for Sotomayor, Black for Jackson)
sameracerespondents.df <- ces_total %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )

# Subsetting to non-same race respondents; this returns all CES respondents who aren't in our same race data frame
# Non-minority nominee years will drop out as binary_positive_race will be NA for those respondents
diffracerespondents.df <- ces_total %>% anti_join(sameracerespondents.df)

# Pooled model (all nominations), race messaging, different race respondents
Pooled.r <- felm(formula_race, data=diffracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=diffracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=diffracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Putting results in stargazer table
total_diffrace <- stargazer(Pooled.r,Sotomayor.r,Jackson.r,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Race Message x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabdiffrace",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Different Race Respondents")

cat(total_diffrace, sep = '\n', file = "Paper/Table_diffrace.tex")

rm(Pooled.r, Sotomayor.r, Jackson.r)

################################################################
# Table G.6: Full race analysis results, same race respondents #
################################################################
# Pooled model (all nominations), race messaging, same race respondents
Pooled.r <- felm(formula_race, data=sameracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=sameracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=sameracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Putting results in stargazer table
total_samerace <- stargazer(Pooled.r,Sotomayor.r,  Jackson.r,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Race Message x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabsamerace",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Same Race Respondents")

cat(total_samerace, sep = '\n', file = "Paper/Table_samerace.tex")

rm(Pooled.r, Sotomayor.r, Jackson.r)

################################################################
# Evaluations of senators, incorporating roll call perceptions #
################################################################
# Regression formulas to use for each year of CES data we have; this includes respondent roll call perceptions
std_formula_2009 <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + latino + chair + votepct +
                              I(arra09==1)+ I(schip09==1) + I(fairpay09==1) + I(climate09==1) + I(health09==1) | respondentid | 0 | respondentid)

std_formula_2010 <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + latino + chair + votepct +I(sotomayor==1) +
                              I(arra==1)+ I(jobs==1) + I(climate==1) + I(health==1) + I(wall_st==1) + I(dontask==1) | respondentid | 0 | respondentid)

std_formula_2020 <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + afam + latino + chair + votepct + I(cares_act==1) +
                              I(heroes_act==1) + I(justice_act==1) + I(kavanaugh==1) + I(remove_trump==1) + I(first_step_act==1) | respondentid | 0 | respondentid)

std_formula_2022 <- formula(senator_approval2 ~ binary_positive_gender*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + afam + latino + chair + votepct + I(covid_relief==1) +
                              I(infrastructure==1) + I(abortion_services==1) + I(dreamers==1) | respondentid | 0 | respondentid)

###########################################
# Table H.1: Sotomayor roll call analysis #
###########################################
# Sotomayor model
Sotomayor.rollcall <- felm(std_formula_2009, data=ces_total %>% filter(nomination == "sotomayor"))

# Putting results in stargazer table
total_s_roll <- stargazer(Sotomayor.rollcall,
                          add.lines=list(c("Respondent Fixed Effects", "\\checkmark" )),
                          notes.append = FALSE, notes.label = "",
                          omit = c("afam"),
                          report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                          omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                          dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                          model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                          covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)",
                                             "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator",
                                             "Woman Senator", "Latino Senator", "Committee Chair",
                                             "Previous General Election Voteshare", "Vote Perception: ARRA",
                                             "Vote Perception: SCHIP","Vote Perception: Fair Pay Act","Vote Perception: Climate Bill", "Vote Perception: Health Bill", 
                                             "Any Positive Gender Message x Copartisan"),
                          notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                          label="tabsroll",
                          digits=2,
                          digits.extra = 0,column.sep.width = "-8pt",
                          title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Controlling for Perceptions of Roll Call Votes: Sotomayor")

cat(total_s_roll , sep = '\n', file = "Paper/Table_sotomayor_rollcall.tex")

#######################################
# Table H.2: Kagan roll call analysis #
#######################################
# Kagan model
Kagan.rollcall <- felm(std_formula_2010, data=ces_total %>% filter(nomination == "kagan"))

# Putting results in stargazer table
total_k_roll <- stargazer(Kagan.rollcall,
                          add.lines=list(c("Respondent Fixed Effects", "\\checkmark" )),
                          notes.append = FALSE, notes.label = "",
                          omit = c("afam"),
                          report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                          omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                          dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                          model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                          covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)",
                                             "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator",
                                             "Woman Senator", "Latino Senator", "Committee Chair",
                                             "Previous General Election Voteshare", "Vote Perception: Sotomayor", "Vote Perception: ARRA",
                                             "Vote Perception: Jobs", "Vote Perception: Climate Bill", "Vote Perception: Health Bill", "Vote Perception: Wall Street",
                                             "Vote Perception: Don't Ask Don't Tell",
                                             "Any Positive Gender Message x Copartisan"),
                          notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                          label="tabkroll",
                          digits=2,
                          digits.extra = 0,column.sep.width = "-8pt",
                          title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Controlling for Perceptions of Roll Call Votes: Kagan")

cat(total_k_roll , sep = '\n', file = "Paper/Table_kagan_rollcall.tex")

#########################################
# Table H.3: Barrett roll call analysis #
#########################################
# Barrett model
Barrett.rollcall <- felm(std_formula_2020, data=ces_total %>% filter(nomination == "barrett"))

# Putting results in stargazer table
total_b_roll <- stargazer(Barrett.rollcall,
                          add.lines=list(c("Respondent Fixed Effects", "\\checkmark" )),
                          notes.append = FALSE, notes.label = "",
                          report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                          omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                          dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                          model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                          covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)",
                                             "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator",
                                             "Woman Senator", "African American Senator", "Latino Senator", "Committee Chair",
                                             "Previous General Election Voteshare", "Vote Perception: Cares Act", "Vote Perception: Heroes Act",
                                             "Vote Perception: Justice Act", "Vote Perception: Kavanaugh", "Vote Perception: Remove Trump", "Vote Perception: First Step Act",
                                             "Any Positive Gender Message x Copartisan"),
                          notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                          label="tabbroll",
                          digits=2,
                          digits.extra = 0,column.sep.width = "-8pt",
                          title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Controlling for Perceptions of Roll Call Votes: Barrett")

cat(total_b_roll , sep = '\n', file = "Paper/Table_barrett_rollcall.tex")

#########################################
# Table H.4: Jackson roll call analysis #
#########################################
# Jackson model
Jackson.rollcall <- felm(std_formula_2022, data=ces_total %>% filter(nomination == "jackson"))

# Putting results in stargazer table
total_j_roll <- stargazer(Jackson.rollcall,
                          add.lines=list(c("Respondent Fixed Effects", "\\checkmark" )),
                          notes.append = FALSE, notes.label = "",
                          report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                          omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                          dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                          model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                          covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)",
                                             "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator",
                                             "Woman Senator", "African American Senator", "Latino Senator", "Committee Chair",
                                             "Previous General Election Voteshare", "Vote Perception: Covid Relief", "Vote Perception: Infrastructure",
                                             "Vote Perception: Abortion Services", "Vote Perception: Dreamers",
                                             "Any Positive Gender Message x Copartisan"),
                          notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                          label="tabjroll",
                          digits=2,
                          digits.extra = 0,column.sep.width = "-8pt",
                          title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Controlling for Perceptions of Roll Call Votes: Jackson")

cat(total_j_roll , sep = '\n', file = "Paper/Table_jackson_rollcall.tex")

#############################################
# Evaluations of senators, by news interest #
#############################################
# Subsetting to high and low news interest
ces_total_newshigh <- ces_total[ces_total$newsint_high==1,]
ces_total_newslow <- ces_total[ces_total$newsint_high==0,]

# Clearing environment of unnecessary objects
rm(list=setdiff(ls(), c("ces_total","ces_total_newshigh","ces_total_newslow", "std_formula", "std_formula_alt","formula_race","formula_race_alt")))

##################################################
# Figure I.1: Gender results, high news interest #
##################################################
# All respondents
# Going to run all of the regressions first, output individual tables, then combine into one figure
Pooled.g <- felm(std_formula, data=ces_total_newshigh)

Sotomayor.g <- felm(std_formula_alt, data=ces_total_newshigh %>% filter(nomination == "sotomayor"))

Kagan.g <- felm(std_formula_alt, data=ces_total_newshigh %>% filter(nomination == "kagan"))

Barrett.g <- felm(std_formula, data=ces_total_newshigh %>% filter(nomination == "barrett"))

Jackson.g <- felm(std_formula, data=ces_total_newshigh %>% filter(nomination == "jackson"))

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf <- mget(ls(pattern = '\\.g'))
results_full <- data.frame()

# For each model, get the coefficients and SEs for the key explanatory variables (positive mention of gender and that interacted with copartisanship)
# Then, put them all together in a dataframe
for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full <- bind_rows(results_full,results)
  results_full$reg <- gsub(".g","",results_full$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Women respondents
woman.respondents <- ces_total_newshigh[which(ces_total_newshigh$woman == 1),]

Pooled.g <- felm(std_formula, woman.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, woman.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, woman.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf<-mget(ls(pattern = '\\.g'))
results_full_women <- data.frame()

# For each model, get the coefficients and SEs for the key explanatory variables (positive mention of gender and that interacted with copartisanship)
# Then, put them all together in a dataframe
for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_women<- bind_rows(results_full_women,results)
  results_full_women$reg <- gsub(".g","",results_full_women$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Men respondents
man.respondents <- ces_total_newshigh[which(ces_total_newshigh$woman == 0),]

Pooled.g <- felm(std_formula, man.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, man.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, man.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf<-mget(ls(pattern = '\\.g'))
results_full_men <- data.frame()

# For each model, get the coefficients and SEs for the key explanatory variables (positive mention of gender and that interacted with copartisanship)
# Then, put them all together in a dataframe
for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_men<- bind_rows(results_full_men,results)
  results_full_men$reg <- gsub(".g","",results_full_men$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Putting all results into same figure
# Labels to our results datasets denoting which sample of respondents they were run on
results_full$gender <- "All Respondents"
results_full_women$gender <- "Women"
results_full_men$gender <- "Men/Non-binary/Other"

# Combining all results together
results_combined <- bind_rows(results_full, results_full_women, results_full_men)

# Cleaner variable names to display
results_combined$term <- rownames(results_combined)
results_combined$term <- gsub("\\.{3}","", results_combined$term)
results_combined$term <- gsub("[0-9]+","", results_combined$term)
results_combined$term[results_combined$term=="binary_positive_gender"] <- "Any Positive Messages"
results_combined$term[results_combined$term=="binary_positive_gender:match_senator_party_leaners"] <- "Any Positive Messages x Copartisan"

# Calculate the 90 and 95 percent confidence intervals
results_combined$lb <- results_combined$coef - qnorm(.975)*results_combined$se
results_combined$ub <- results_combined$coef + qnorm(.975)*results_combined$se
results_combined$lb2 <- results_combined$coef - qnorm(.95)*results_combined$se
results_combined$ub2 <- results_combined$coef + qnorm(.95)*results_combined$se

# Factorizing variable names
results_combined$term <- as.character(results_combined$term)
results_combined$term <- as.factor(results_combined$term)

# Factorizing context name
results_combined <- results_combined %>%
  mutate(reg = fct_relevel(reg, "Jackson","Barrett","Kagan","Sotomayor","Pooled"))

# Making the figure
fig_gender <- ggplot(results_combined, aes(x = reg, y = coef, group=term, color=term)) +
  geom_point(size=2,position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0.1, position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb2, ymax = ub2), linewidth=1, width = 0, position=position_dodge(width=0.5)) +
  geom_hline(yintercept = 0, lty = 2) +
  xlab("Nominee") + theme_bw() + 
  ylab("Coefficient Estimate") +
  coord_flip() + labs(title="") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.title=element_blank())+ facet_grid(. ~ gender)+ scale_color_manual(values=c("#999999", "mediumpurple4")) +
  theme(legend.position = "bottom")

# Outputting
ggsave("Paper/Figure1_News.png", fig_gender, width = 10, height = 7) 

rm(results,results_full,results_combined,results_full_men,results_full_women,man.respondents,woman.respondents)

################################################
# Figure I.2: Race results, high news interest #
################################################
# Aggregate, race messaging
Pooled.r <- felm(formula_race, data=ces_total_newshigh)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=ces_total_newshigh %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=ces_total_newshigh %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf <- mget(ls(pattern = '\\.r'))
results_full <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full <- bind_rows(results_full,results)
  results_full$reg <- gsub(".r","",results_full$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Same race respondents
sameracerespondents.df <- ces_total_newshigh %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )

Pooled.r <- felm(formula_race, data=sameracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=sameracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=sameracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf <- mget(ls(pattern = '\\.r'))
results_full_samerace <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_samerace <- bind_rows(results_full_samerace,results)
  results_full_samerace$reg <- gsub(".r","",results_full_samerace$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Different race respondents
diffracerespondents.df <- ces_total_newshigh %>% anti_join(sameracerespondents.df)

# Aggregate, race messaging
Pooled.r <- felm(formula_race, data=diffracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=diffracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=diffracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf <- mget(ls(pattern = '\\.r'))
results_full_diffrace <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_diffrace <- bind_rows(results_full_diffrace,results)
  results_full_diffrace$reg <- gsub(".r","",results_full_diffrace$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Putting all results into same figure
# Labels to our results datasets denoting which sample of respondents they were run on
results_full$race <- "All Respondents"
results_full_samerace$race <- "Same Race Respondents"
results_full_diffrace$race <- "Different Race Respondents"

# Combining all results together
results_combined <- bind_rows(results_full, results_full_samerace, results_full_diffrace)

# Cleaner variable names to display
results_combined$term <- rownames(results_combined)
results_combined$term <- gsub("\\.{3}","", results_combined$term)
results_combined$term <- gsub("[0-9]+","", results_combined$term)
results_combined$term[results_combined$term=="binary_positive_race"] <- "Any Positive Messages"
results_combined$term[results_combined$term=="binary_positive_race:match_senator_party_leaners"] <- "Any Positive Messages x Copartisan"

# Calculate the 90 and 95 percent confidence intervals
results_combined$lb <- results_combined$coef - qnorm(.975)*results_combined$se
results_combined$ub <- results_combined$coef + qnorm(.975)*results_combined$se
results_combined$lb2 <- results_combined$coef - qnorm(.95)*results_combined$se
results_combined$ub2 <- results_combined$coef + qnorm(.95)*results_combined$se

results_combined$term <- as.character(results_combined$term)
results_combined$term <- as.factor(results_combined$term)

results_combined <- results_combined %>%
  mutate(reg = fct_relevel(reg, "Jackson","Sotomayor","Pooled"))

# Making the figure
fig_race <- ggplot(results_combined, aes(x = reg, y = coef, group=term, color=term)) +
  geom_point(size=2,position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0.1, position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb2, ymax = ub2), linewidth=1, width = 0, position=position_dodge(width=0.5)) +
  geom_hline(yintercept = 0, lty = 2) +
  xlab("Nominee") + theme_bw() + 
  ylab("Coefficient Estimate") +
  coord_flip() + labs(title="") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.title=element_blank())+ facet_grid(. ~ race)+ scale_color_manual(values=c("#999999", "mediumpurple4")) +
  theme(legend.position = "bottom")

# Outputting
ggsave("Paper/Figure2_News.png", fig_race, width = 10, height = 7) 

#################################################
# Figure I.3: Gender results, low news interest #
#################################################
rm(list=setdiff(ls(), c("ces_total","ces_total_newshigh","ces_total_newslow","std_formula","std_formula_alt","formula_race","formula_race_alt")))

# Aggregate, gender messaging
# Going to run all of the regressions first, output individual tables, then combine into one figure
Pooled.g <- felm(std_formula, data=ces_total_newslow)

Sotomayor.g <- felm(std_formula_alt, data=ces_total_newslow %>% filter(nomination == "sotomayor"))

Kagan.g <- felm(std_formula_alt, data=ces_total_newslow %>% filter(nomination == "kagan"))

Barrett.g <- felm(std_formula, data=ces_total_newslow %>% filter(nomination == "barrett"))

Jackson.g <- felm(std_formula, data=ces_total_newslow %>% filter(nomination == "jackson"))

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf <- mget(ls(pattern = '\\.g'))
results_full <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full <- bind_rows(results_full,results)
  results_full$reg <- gsub(".g","",results_full$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Women respondents
woman.respondents <- ces_total_newslow[which(ces_total_newslow$woman == 1),]

Pooled.g <- felm(std_formula, woman.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, woman.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, woman.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, woman.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf <- mget(ls(pattern = '\\.g'))
results_full_women <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_women<- bind_rows(results_full_women,results)
  results_full_women$reg <- gsub(".g","",results_full_women$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Men respondents
man.respondents <- ces_total_newslow[which(ces_total_newslow$woman == 0),]

Pooled.g <- felm(std_formula, man.respondents)
summary(Pooled.g)

Sotomayor.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "sotomayor"))
summary(Sotomayor.g)

Kagan.g <- felm(std_formula_alt, man.respondents %>% filter(nomination == "kagan"))
summary(Kagan.g)

Barrett.g <- felm(std_formula, man.respondents %>% filter(nomination == "barrett"))
summary(Barrett.g)

Jackson.g <- felm(std_formula, man.respondents %>% filter(nomination == "jackson"))
summary(Jackson.g)

# Extract the coefficients from all of the model objects in the R environment (denoted by .g)
Listdf <- mget(ls(pattern = '\\.g'))
results_full_men <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_gender"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_gender:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_gender:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_men<- bind_rows(results_full_men,results)
  results_full_men$reg <- gsub(".g","",results_full_men$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.g, Sotomayor.g, Kagan.g, Barrett.g, Jackson.g)

# Putting all results into same figure
# Labels to our results datasets denoting which sample of respondents they were run on
results_full$gender <- "All Respondents"
results_full_women$gender <- "Women"
results_full_men$gender <- "Men/Non-binary/Other"

# Combining all results together
results_combined <- bind_rows(results_full, results_full_women, results_full_men)

# Cleaner variable names to display
results_combined$term <- rownames(results_combined)
results_combined$term <- gsub("\\.{3}","", results_combined$term)
results_combined$term <- gsub("[0-9]+","", results_combined$term)
results_combined$term[results_combined$term=="binary_positive_gender"] <- "Any Positive Messages"
results_combined$term[results_combined$term=="binary_positive_gender:match_senator_party_leaners"] <- "Any Positive Messages x Copartisan"

# Calculate the 90 and 95 percent confidence intervals
results_combined$lb <- results_combined$coef - qnorm(.975)*results_combined$se
results_combined$ub <- results_combined$coef + qnorm(.975)*results_combined$se
results_combined$lb2 <- results_combined$coef - qnorm(.95)*results_combined$se
results_combined$ub2 <- results_combined$coef + qnorm(.95)*results_combined$se

results_combined$term <- as.character(results_combined$term)
results_combined$term <- as.factor(results_combined$term)

results_combined <- results_combined %>%
  mutate(reg = fct_relevel(reg, 
                           "Jackson","Barrett","Kagan","Sotomayor","Pooled"))

# Making the figure
fig_gender <- ggplot(results_combined, aes(x = reg, y = coef, group=term, color=term)) +
  geom_point(size=2,position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0.1, position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb2, ymax = ub2), linewidth=1, width = 0, position=position_dodge(width=0.5)) +
  geom_hline(yintercept = 0, lty = 2) +
  xlab("Nominee") + theme_bw() + 
  ylab("Coefficient Estimate") +
  coord_flip() + labs(title="") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.title=element_blank())+ facet_grid(. ~ gender)+ scale_color_manual(values=c("#999999", "mediumpurple4")) +
  theme(legend.position = "bottom")

# Outputting
ggsave("Paper/Figure1_Newslow.png", fig_gender, width = 10, height = 7) 

rm(results,results_full,results_combined,results_full_men,results_full_women,man.respondents,woman.respondents)

###############################################
# Figure I.4: Race results, low news interest #
###############################################
# Aggregate, race messaging
Pooled.r <- felm(formula_race, data=ces_total_newslow)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=ces_total_newslow %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=ces_total_newslow %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf <- mget(ls(pattern = '\\.r'))
results_full <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full <- bind_rows(results_full,results)
  results_full$reg <- gsub(".r","",results_full$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Same race
sameracerespondents.df <- ces_total_newslow %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )

Pooled.r <- felm(formula_race, data=sameracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=sameracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=sameracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf<-mget(ls(pattern = '\\.r'))
results_full_samerace <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_samerace <- bind_rows(results_full_samerace,results)
  results_full_samerace$reg <- gsub(".r","",results_full_samerace$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Different race
diffracerespondents.df <- ces_total_newslow %>% anti_join(sameracerespondents.df)

# Aggregate, race messaging
Pooled.r <- felm(formula_race, data=diffracerespondents.df)
summary(Pooled.r)

Sotomayor.r <- felm(formula_race_alt, data=diffracerespondents.df %>% filter(nomination == "sotomayor"))
summary(Sotomayor.r)

Jackson.r <- felm(formula_race, data=diffracerespondents.df %>% filter(nomination == "jackson"))
summary(Jackson.r)

# Extract the coefficients from all of the model objects in the R environment (denoted by .r)
Listdf<-mget(ls(pattern = '\\.r'))
results_full_diffrace <- data.frame()

for(i in 1:length(Listdf)){
  df_obj <- Listdf[[i]]
  coef1 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race"])
  colnames(coef1)[1] <- "coef"
  se1 <- data.frame(df_obj$cse["binary_positive_race"])
  colnames(se1)[1] <- "se"
  coef2 <- data.frame(df_obj$coefficients[rownames(df_obj$coefficients) == "binary_positive_race:match_senator_party_leaners"])
  colnames(coef2)[1] <- "coef"
  se2 <- data.frame(df_obj$cse["binary_positive_race:match_senator_party_leaners"])
  colnames(se2)[1] <- "se"
  coefs <- bind_rows(coef1, coef2)
  ses <- bind_rows(se1, se2)
  results <- bind_cols(coefs, ses)
  results$reg <- names(Listdf)[i]
  results_full_diffrace <- bind_rows(results_full_diffrace,results)
  results_full_diffrace$reg <- gsub(".r","",results_full_diffrace$reg,fixed = TRUE)
}

rm(coef1, se1, coef2, se2, coefs, ses, Pooled.r, Sotomayor.r, Jackson.r)

# Putting all results into same figure
# Labels to our results datasets denoting which sample of respondents they were run on
results_full$race <- "All Respondents"
results_full_samerace$race <- "Same Race Respondents"
results_full_diffrace$race <- "Different Race Respondents"

# Combining all results together
results_combined <- bind_rows(results_full, results_full_samerace, results_full_diffrace)

# Cleaner variable names to display
results_combined$term <- rownames(results_combined)
results_combined$term <- gsub("\\.{3}","", results_combined$term)
results_combined$term <- gsub("[0-9]+","", results_combined$term)
results_combined$term[results_combined$term=="binary_positive_race"] <- "Any Positive Messages"
results_combined$term[results_combined$term=="binary_positive_race:match_senator_party_leaners"] <- "Any Positive Messages x Copartisan"

# Calculate the 90 and 95 percent confidence intervals
results_combined$lb <- results_combined$coef - qnorm(.975)*results_combined$se
results_combined$ub <- results_combined$coef + qnorm(.975)*results_combined$se
results_combined$lb2 <- results_combined$coef - qnorm(.95)*results_combined$se
results_combined$ub2 <- results_combined$coef + qnorm(.95)*results_combined$se

results_combined$term <- as.character(results_combined$term)
results_combined$term <- as.factor(results_combined$term)

results_combined <- results_combined %>%
  mutate(reg = fct_relevel(reg, "Jackson","Sotomayor","Pooled"))

# Making the figure
fig_race <- ggplot(results_combined, aes(x = reg, y = coef, group=term, color=term)) +
  geom_point(size=2,position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0.1, position=position_dodge(width=0.5)) +
  geom_errorbar(aes(ymin = lb2, ymax = ub2), linewidth=1, width = 0, position=position_dodge(width=0.5)) +
  geom_hline(yintercept = 0, lty = 2) +
  xlab("Nominee") + theme_bw() + 
  ylab("Coefficient Estimate") +
  coord_flip() + labs(title="") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.title=element_blank())+ facet_grid(. ~ race)+ scale_color_manual(values=c("#999999", "mediumpurple4")) +
  theme(legend.position = "bottom")

# Outputting
ggsave("Paper/Figure2_Newslow.png", fig_race, width = 10, height = 7) 

#######################################################
# Evaluations of senators, binary measure of approval #
#######################################################
# Regression formulas to use, binary outcome variable
binary_formula <- formula(binary_senator_approval ~ binary_positive_gender*match_senator_party_leaners +
                            I(log(total_nominee_messages + 0.01)) +
                            extremity + seniority + I(seniority^2) + majority +
                            female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
binary_formula_race <- formula(binary_senator_approval ~ binary_positive_race*match_senator_party_leaners +
                                 I(log(total_nominee_messages + 0.01)) +
                                 extremity + seniority + I(seniority^2) + majority +
                                 female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
# Without afam
binary_formula_alt <- formula(binary_senator_approval ~ binary_positive_gender*match_senator_party_leaners +
                            I(log(total_nominee_messages + 0.01)) +
                            extremity + seniority + I(seniority^2) + majority +
                            female + latino + votepct + chair | respondentid | 0 | respondentid)
binary_formula_race_alt <- formula(binary_senator_approval ~ binary_positive_race*match_senator_party_leaners +
                                 I(log(total_nominee_messages + 0.01)) +
                                 extremity + seniority + I(seniority^2) + majority +
                                 female + latino + votepct + chair | respondentid | 0 | respondentid)

###############################################################
# Table J.1: Gender, all respondents, binary approval outcome #
###############################################################
basic.lm.gender <- felm(binary_formula, data=ces_total)
summary(basic.lm.gender)

gender.s <- felm(binary_formula_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(binary_formula_alt, data=ces_total %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(binary_formula, data=ces_total %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(binary_formula, data=ces_total %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_full <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                        covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Gender Message x Copartisan"),
                        notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabgender_binary",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Gender, Copartisanship, and Senator Approval using a Binary Measure of Approval")

cat(total_full, sep = '\n', file = "Paper/Table_full_gender_binary.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

###############################################################
# Table J.2: Gender, men respondents, binary approval outcome #
###############################################################
# Men respondents
man.respondents <- ces_total[which(ces_total$woman == 0),]

basic.lm.gender <- felm(binary_formula, data=man.respondents)
summary(basic.lm.gender)

gender.s <- felm(binary_formula_alt, data=man.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(binary_formula_alt, data=man.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(binary_formula, data=man.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(binary_formula, data=man.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_men <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                       add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                       notes.append = FALSE, notes.label = "",
                       report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                       omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                       dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                       model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                       covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare","Committee Chair", "Any Positive Gender Message x Copartisan"),
                       notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                       label="tabmen_binary",
                       digits=2,
                       digits.extra = 0,column.sep.width = "-8pt",
                       title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Men using a Binary Measure of Approval")

cat(total_men, sep = '\n', file = "Paper/Table_men_gender_binary.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#################################################################
# Table J.3: Gender, women respondents, binary approval outcome #
#################################################################
# Women respondents
woman.respondents <- ces_total[which(ces_total$woman == 1),]

basic.lm.gender <- felm(binary_formula, data=woman.respondents)
summary(basic.lm.gender)

gender.s <- felm(binary_formula_alt, data=woman.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(binary_formula_alt, data=woman.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(binary_formula, data=woman.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(binary_formula, data=woman.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_women <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                         add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                         notes.append = FALSE, notes.label = "",
                         report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                         omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                         dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                         model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                         covariate.labels=c("Any Positive Gender Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Gender Message x Copartisan"),
                         notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                         label="tabwomen_binary",
                         digits=2,
                         digits.extra = 0,column.sep.width = "-8pt",
                         title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Women using a Binary Measure of Approval")

cat(total_women, sep = '\n', file = "Paper/Table_women_gender_binary.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#############################################################
# Table J.4: Race, all respondents, binary approval outcome #
#############################################################
basic.lm.race <- felm(binary_formula_race, data=ces_total)
summary(basic.lm.race)

race.sotomayor <- felm(binary_formula_race_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(binary_formula_race, data=ces_total %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_race <- stargazer(basic.lm.race,race.sotomayor,  race.jackson,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                        covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Race Message x Copartisan"),
                        notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabrace_binary",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Race, Copartisanship, and Senator Approval using a Binary Measure of Approval")

cat(total_race, sep = '\n', file = "Paper/Table_full_race_binary.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

########################################################################
# Table J.5: Race, different race respondents, binary approval outcome #
########################################################################
samerace.respondents.df <- ces_total %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )
diffrace.respondents.df <- ces_total %>% anti_join(samerace.respondents.df)

basic.lm.race <- felm(binary_formula_race, data=diffrace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(binary_formula_race_alt, data=diffrace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(binary_formula_race, data=diffrace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_diffrace <- stargazer(basic.lm.race, race.sotomayor, race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Any Positive Race Message x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabdiffrace_binary",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Different Race Respondents using a Binary Measure of Approval")

cat(total_diffrace, sep = '\n', file = "Paper/Table_diffrace_binary.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

###################################################################
# Table J.6: Race, same race respondents, binary approval outcome #
###################################################################
basic.lm.race <- felm(binary_formula_race, data=samerace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(binary_formula_race_alt, data=samerace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(binary_formula_race, data=samerace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_samerace <- stargazer(basic.lm.race,race.sotomayor,  race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (0/1)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Any Positive Race Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare","Committee Chair", "Any Positive Race Message x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabsamerace_binary",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Same Race Respondents using a Binary Measure of Approval")

cat(total_samerace, sep = '\n', file = "Paper/Table_samerace_binary.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

##############################################################
# Evaluations of senators, alternative explanatory variables #
##############################################################
#######################################################
# Total press releases as the EV (rather than binary) #
#######################################################
# New regression formulas with total number instead of binary
total_formula <- formula(senator_approval2 ~ number_positive_gender*match_senator_party_leaners +
                           I(log(total_nominee_messages + 0.01)) +
                           extremity + seniority + I(seniority^2) + majority +
                           female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
total_formula_race <- formula(senator_approval2 ~ number_positive_race*match_senator_party_leaners +
                                I(log(total_nominee_messages + 0.01)) +
                                extremity + seniority + I(seniority^2) + majority +
                                female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
# Without afam
total_formula_alt <- formula(senator_approval2 ~ number_positive_gender*match_senator_party_leaners +
                           I(log(total_nominee_messages + 0.01)) +
                           extremity + seniority + I(seniority^2) + majority +
                           female + latino + votepct + chair | respondentid | 0 | respondentid)
total_formula_race_alt <- formula(senator_approval2 ~ number_positive_race*match_senator_party_leaners +
                                I(log(total_nominee_messages + 0.01)) +
                                extremity + seniority + I(seniority^2) + majority +
                                female + latino + votepct + chair | respondentid | 0 | respondentid)

#######################################################
# Table K.1: Gender, all respondents, total number EV #
#######################################################
basic.lm.gender <- felm(total_formula, data=ces_total)
summary(basic.lm.gender)

gender.s <- felm(total_formula_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(total_formula_alt, data=ces_total %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(total_formula, data=ces_total %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(total_formula, data=ces_total %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_full <- stargazer(basic.lm.gender, gender.s, gender.k, gender.b, gender.j,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                        covariate.labels=c("Positive Gender Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Positive Gender Messages x Copartisan"),
                        notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabgender_total",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Gender, Copartisanship, and Senator Approval using Total Messages")

cat(total_full, sep = '\n', file = "Paper/Table_full_gender_total.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#######################################################
# Table K.2: Gender, men respondents, total number EV #
#######################################################
# Men respondents
man.respondents <- ces_total[which(ces_total$woman == 0),]

basic.lm.gender <- felm(total_formula, man.respondents)
summary(basic.lm.gender)

gender.s <- felm(total_formula_alt, man.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(total_formula_alt, man.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(total_formula, man.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(total_formula, man.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_men <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                       add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                       notes.append = FALSE, notes.label = "",
                       report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                       omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                       dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                       model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                       covariate.labels=c("Positive Gender Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Positive Gender Messages x Copartisan"),
                       notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                       label="tabmen_total",
                       digits=2,
                       digits.extra = 0,column.sep.width = "-8pt",
                       title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Men using Total Messages")

cat(total_men, sep = '\n', file = "Paper/Table_men_gender_total.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#########################################################
# Table K.3: Gender, women respondents, total number EV #
#########################################################
# Women respondents
woman.respondents <- ces_total[which(ces_total$woman == 1),]

basic.lm.gender <- felm(total_formula, woman.respondents)
summary(basic.lm.gender)

gender.s <- felm(total_formula_alt, woman.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(total_formula_alt, woman.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(total_formula, woman.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(total_formula, woman.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_women <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                         add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                         notes.append = FALSE, notes.label = "",
                         report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                         omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                         dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                         model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                         covariate.labels=c("Positive Gender Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare","Committee Chair", "Positive Gender Messages x Copartisan"),
                         notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                         label="tabwomen_total",
                         digits=2,
                         digits.extra = 0,column.sep.width = "-8pt",
                         title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Women using Total Messages")

cat(total_women, sep = '\n', file = "Paper/Table_women_gender_total.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#####################################################
# Table K.4: Race, all respondents, total number EV #
#####################################################
basic.lm.race <- felm(total_formula_race, data=ces_total)
summary(basic.lm.race)

race.sotomayor <- felm(total_formula_race_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(total_formula_race, data=ces_total %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_race <- stargazer(basic.lm.race,race.sotomayor,race.jackson,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                        covariate.labels=c("Positive Race Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Positive Race Messages x Copartisan"),
                        notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabrace_total",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Race, Copartisanship, and Senator Approval using Total Messages")

cat(total_race, sep = '\n', file = "Paper/Table_full_race_total.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

################################################################
# Table K.5: Race, different race respondents, total number EV #
################################################################
# Same race respondents
samerace.respondents.df <- ces_total %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )
# Different race respondents
diffrace.respondents.df <- ces_total %>% anti_join(samerace.respondents.df)

basic.lm.race <- felm(total_formula_race, data=diffrace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(total_formula_race_alt, data=diffrace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(total_formula_race, data=diffrace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_diffrace <- stargazer(basic.lm.race,race.sotomayor,race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Positive Race Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Positive Race Messages x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabdiffrace_total",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Different Race Respondents using Total Messages")

cat(total_diffrace, sep = '\n', file = "Paper/Table_diffrace_total.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

###########################################################
# Table K.6: Race, same race respondents, total number EV #
###########################################################
basic.lm.race <- felm(total_formula_race, data=samerace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(total_formula_race_alt, data=samerace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(total_formula_race, data=samerace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_samerace <- stargazer(basic.lm.race,race.sotomayor,race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("Positive Race Messages", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "Positive Race Messages x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests).  We subset messages to only include those that are positive about the nominee.}",
                            label="tabsamerace_total",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Same Race Respondents using Total Messages")

cat(total_samerace, sep = '\n', file = "Paper/Table_samerace_total.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

##############################################################
# Logged total press releases as the EV (rather than binary) #
##############################################################
# Creating logged measure of total messages
ces_total$log_positive_gender_discussion <- log(ces_total$number_positive_gender + 0.01)
ces_total$log_positive_race_discussion <- log(ces_total$number_positive_race + 0.01)

# New regression formulas
log_formula <- formula(senator_approval2 ~ log_positive_gender_discussion*match_senator_party_leaners +
                         I(log(total_nominee_messages + 0.01)) +
                         extremity + seniority + I(seniority^2) + majority +
                         female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
log_formula_race <- formula(senator_approval2 ~ log_positive_race_discussion*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + afam + latino + votepct + chair | respondentid | 0 | respondentid)
# Without afam
log_formula_alt <- formula(senator_approval2 ~ log_positive_gender_discussion*match_senator_party_leaners +
                         I(log(total_nominee_messages + 0.01)) +
                         extremity + seniority + I(seniority^2) + majority +
                         female + latino + votepct + chair | respondentid | 0 | respondentid)
log_formula_race_alt <- formula(senator_approval2 ~ log_positive_race_discussion*match_senator_party_leaners +
                              I(log(total_nominee_messages + 0.01)) +
                              extremity + seniority + I(seniority^2) + majority +
                              female + latino + votepct + chair | respondentid | 0 | respondentid)

########################################################
# Table K.7: Gender, all respondents, logged number EV #
########################################################
basic.lm.gender <- felm(log_formula, data=ces_total)
summary(basic.lm.gender)

gender.s <- felm(log_formula_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(log_formula_alt, data=ces_total %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(log_formula, data=ces_total %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(log_formula, data=ces_total %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_full <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                        covariate.labels=c("ln(Positive Gender Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "ln(Positive Gender Messages) x Copartisan"),
                        notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabgender_log",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Gender, Copartisanship, and Senator Approval using Logged Messages")

cat(total_full, sep = '\n', file = "Paper/Table_full_gender_log.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

########################################################
# Table K.8: Gender, men respondents, logged number EV #
########################################################
# Men respondents
man.respondents <- ces_total[which(ces_total$woman == 0),]

basic.lm.gender <- felm(log_formula, man.respondents)
summary(basic.lm.gender)

gender.s <- felm(log_formula_alt, man.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(log_formula_alt, man.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(log_formula, man.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(log_formula, man.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_men <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                       add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                       notes.append = FALSE, notes.label = "",
                       report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                       omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                       dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                       model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                       covariate.labels=c("ln(Positive Gender Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "ln(Positive Gender Messages) x Copartisan"),
                       notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                       label="tabmen_log",
                       digits=2,
                       digits.extra = 0,column.sep.width = "-8pt",
                       title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Men using Logged Messages")

cat(total_men, sep = '\n', file = "Paper/Table_men_gender_log.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

##########################################################
# Table K.9: Gender, women respondents, logged number EV #
##########################################################
# Women respondents
woman.respondents <- ces_total[which(ces_total$woman == 1),]

basic.lm.gender <- felm(log_formula, woman.respondents)
summary(basic.lm.gender)

gender.s <- felm(log_formula_alt, woman.respondents %>% filter(nomination == "sotomayor"))
summary(gender.s)

gender.k <- felm(log_formula_alt, woman.respondents %>% filter(nomination == "kagan"))
summary(gender.k)

gender.b <- felm(log_formula, woman.respondents %>% filter(nomination == "barrett"))
summary(gender.b)

gender.j <- felm(log_formula, woman.respondents %>% filter(nomination == "jackson"))
summary(gender.j)

# Putting results in stargazer table
total_women <- stargazer(basic.lm.gender,gender.s, gender.k, gender.b, gender.j,
                         add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" , "\\checkmark", "\\checkmark")),
                         notes.append = FALSE, notes.label = "",
                         report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                         omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                         dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                         model.numbers = TRUE, column.labels=c("Pooled","Sotomayor", "Kagan", "Barrett", "Jackson"),
                         covariate.labels=c("ln(Positive Gender Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "ln(Positive Gender Messages) x Copartisan"),
                         notes="\\parbox[t]{.8\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                         label="tabwomen_log",
                         digits=2,
                         digits.extra = 0,column.sep.width = "-8pt",
                         title="Discussion of Nominee Gender, Copartisanship, and Senator Approval Among Women using Logged Messages")

cat(total_women, sep = '\n', file = "Paper/Table_women_gender_log.tex")

rm(basic.lm.gender, gender.s, gender.k, gender.b, gender.j)

#######################################################
# Table K.10: Race, all respondents, logged number EV #
#######################################################
basic.lm.race <- felm(log_formula_race, data=ces_total)
summary(basic.lm.race)

race.sotomayor <- felm(log_formula_race_alt, data=ces_total %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(log_formula_race, data=ces_total %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_race <- stargazer(basic.lm.race,race.sotomayor,  race.jackson,
                        add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                        notes.append = FALSE, notes.label = "",
                        report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                        omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                        dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                        model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                        covariate.labels=c("ln(Positive Race Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "ln(Positive Race Messages) x Copartisan"),
                        notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                        label="tabrace_log",
                        digits=2,
                        digits.extra = 0,column.sep.width = "-8pt",
                        title="Discussion of Nominee Race, Copartisanship, and Senator Approval using Logged Messages")

cat(total_race, sep = '\n', file = "Paper/Table_full_race_log.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

##################################################################
# Table K.11: Race, different race respondents, logged number EV #
##################################################################
# Same race respondents
samerace.respondents.df <- ces_total %>% filter( (hispanic == 1 & year == 2009) | (black == 1 & year == 2022) )
# Different race respondents
diffrace.respondents.df <- ces_total %>% anti_join(samerace.respondents.df)

basic.lm.race <- felm(log_formula_race, data=diffrace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(log_formula_race_alt, data=diffrace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(log_formula_race, data=diffrace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_diffrace <- stargazer(basic.lm.race,race.sotomayor,race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("ln(Positive Race Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator", "Previous Voteshare","Committee Chair", "ln(Positive Race Messages) x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabdiffrace_log",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Different Race Respondents using Logged Messages")

cat(total_diffrace, sep = '\n', file = "Paper/Table_diffrace_log.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

#############################################################
# Table K.12: Race, same race respondents, logged number EV #
#############################################################
basic.lm.race <- felm(log_formula_race, data=samerace.respondents.df)
summary(basic.lm.race)

race.sotomayor <- felm(log_formula_race_alt, data=samerace.respondents.df %>% filter(nomination == "sotomayor"))
summary(race.sotomayor)

race.jackson <- felm(log_formula_race, data=samerace.respondents.df %>% filter(nomination == "jackson"))
summary(race.jackson)

# Putting results in stargazer table
total_samerace <- stargazer(basic.lm.race,race.sotomayor,  race.jackson,
                            add.lines=list(c("Respondent Fixed Effects", "\\checkmark" , "\\checkmark", "\\checkmark" )),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "footnotesize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Pooled","Sotomayor","Jackson"),
                            covariate.labels=c("ln(Positive Race Messages)", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair", "ln(Positive Race Messages) x Copartisan"),
                            notes="\\parbox[t]{.68\\textwidth}{\\footnotesize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on respondent) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests).  We subset messages to only include those that are positive about the nominee.}",
                            label="tabsamerace_log",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Race, Copartisanship, and Senator Approval Among Same Race Respondents using Logged Messages")

cat(total_samerace, sep = '\n', file = "Paper/Table_samerace_log.tex")

rm(basic.lm.race, race.sotomayor, race.jackson)

################################################################################################################
# Table L.1: Evaluations of senators, alternative approach with state-year FEs and respondent-level covariates #
################################################################################################################
# Formula for alternative model
# Regression formula, respondent-level predictors (factored), state-year fixed effects, no instrumenting, clustered SEs by respondent
st_yr_formula <- formula(senator_approval2 ~ binary_positive_trait*match_senator_party_leaners +
                           I(log(total_nominee_messages + 0.01)) +
                           extremity + seniority + I(seniority^2) + majority +
                           female + afam + latino + votepct + chair +
                           factor(educ2) + factor(race_alt) + factor(pid3_alt) + factor(faminc2) + age + woman | state_year | 0 | respondentid)

# Setting gender to be the "binary_positive_trait" we use in the regression
ces_total$binary_positive_trait <- ces_total$binary_positive_gender

# Alternative gender model with state-year fixed effects, respondent covariates
alt.gender <- felm(st_yr_formula, data=ces_total)
summary(alt.gender)

# Setting race to be the "binary_positive_trait" we use in the regression
ces_total$binary_positive_trait <- ces_total$binary_positive_race

# Alternative race model with state-year fixed effects, respondent covariates
alt.race <- felm(st_yr_formula, data=ces_total)
summary(alt.race)

# Putting results in stargazer table
table_altmodel <- stargazer(alt.gender, alt.race,
                            add.lines=list(c("State-Year Fixed Effects", "\\checkmark" , "\\checkmark")),
                            notes.append = FALSE, notes.label = "",
                            report="vc*s",star.char=c("*","**"),star.cutoffs = c(0.10,0.05),no.space = TRUE,
                            omit.stat = c("rsq", "ser","f"), font.size = "scriptsize",
                            dep.var.caption  = "Senator Approval (4 Point)", dep.var.labels = "",
                            model.numbers = TRUE, column.labels=c("Gender","Race"),
                            covariate.labels=c("Any Positive Trait Message", "Copartisan","ln(Total No. Senator Messages)", "Senator Extremity", "Seniority", "Seniority$^2$", "Majority Party Senator", "Woman Senator", "African American Senator", "Latino Senator","Previous Voteshare", "Committee Chair",
                                               "Less than 4 Years of College", "Black", "Hispanic", "Mixed/Other", "White", "Independent (Excluding Leaners)/Not Sure",
                                               "Republican", "Income: Less than 70k", "Income: Prefer Not to Say", "Age", "Woman",
                                               "Any Positive Trait Message x Copartisan"),
                            notes="\\parbox[t]{.7\\textwidth}{\\scriptsize \\textit{Note}: Entries are linear regression coefficients with standard errors
                                  (clustered on state) shown in parentheses. $^*$ indicates $p<0.10$ and $^{**} p<0.05$ (two tailed tests). We subset messages to only include those that are positive about the nominee.}",
                            label="tabaltspec",
                            digits=2,
                            digits.extra = 0,column.sep.width = "-8pt",
                            title="Discussion of Nominee Trait, Copartisanship, and Senator Approval, Alternative Pooled Specification")

cat(table_altmodel, sep = '\n', file = "Paper/Table_altspec.tex")
